package nc.hw;

public class HJ39 {

    private static int checkIsSameSubNet(String mark, String ip1, String ip2) {
        if (!checkIpCorrect(ip1) || !checkIpCorrect(ip2) || !checkIpCorrect(mark)) {
            return 1;
        }
        if (!checkMarkCorrect(mark)) {
            return 1;
        }
        int[] ipv1 = new int[4];
        int[] ipv2 = new int[4];
        int[] marks = new int[4];
        String[] split = mark.split("\\.");
        for (int i = 0; i < split.length; i++) {
            marks[i] = Integer.parseInt(split[i]);
        }
        String[] ip1s = ip1.split("\\.");
        for (int i = 0; i < ip1s.length; i++) {
            int i1 = Integer.parseInt(ip1s[i]);
            i1 = i1 & marks[i];
            ipv1[i] = i1;
        }
        String[] ip2s = ip2.split("\\.");
        for (int i = 0; i < ip2s.length; i++) {
            int i1 = Integer.parseInt(ip2s[i]);
            i1 = i1 & marks[i];
            ipv2[i] = i1;
        }
        for (int i = 0; i < 4; i++) {
            if (ipv1[i] != ipv2[i]) {
                return 2;
            }
        }
        return 0;
    }

    private static boolean checkIpCorrect(String ip) {
        if (!ip.matches("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})")) {
            return false;
        }
        String[] split = ip.split("\\.");
        for (String s : split) {
            // 只能是0-255之间的值
            if (Integer.parseInt(s) > 255) {
                return false;
            }
        }
        return true;
    }

    private static boolean checkMarkCorrect(String mark) {
        String[] split = mark.split("\\.");
        StringBuilder sb = new StringBuilder();
        for (String s : split) {
            int i = Integer.parseInt(s);
            String s1 = Integer.toBinaryString(i);
            for (int j = s1.length(); j < 8; j++) {
                sb.append("0");
            }
            sb.append(s1);
        }
        int i = sb.indexOf("0");
        int i1 = sb.lastIndexOf("1");
        return i > i1;
    }

    public static void main(String[] args) {

        System.out.println(checkIsSameSubNet("255.255.255.0", "192.168.224.256", "192.168.10.4"));
        System.out.println(checkIsSameSubNet("255.0.0.0", "193.194.202.15", "232.43.7.59"));
        System.out.println(checkIsSameSubNet("255.255.255.0", "192.168.0.254", "192.168.0.1"));
    }

}
